'''
Created on 09-09-24

@author: peterd
'''

from __future__ import division
import re

from geo.config import RADIUS_UNIT_LIST, RADIUS_LIST
from infra.util.geoutil import getBoundingBox

# rectangle interleave coeficient for distance over 1000m
RIC = 1.422


class Distance:
	def __init__(self, val, unit):
		self.val_ = val
		self.unit_ = unit
		
		
	def toM(self):
		rv = self.val_
		if self.unit_ == 'km':
			rv *= 1000
		return rv
		

	def toKm(self):
		rv = self.val_
		if self.unit_ == 'm':
			rv /= 1000
		return rv


	def toString(self):
		return '%s%s' % (self.val_, self.unit_)
	
	
	def unit(self):
		return self.unit_
	
	
	def value(self):
		return self.val_



class InvalidRadiusUnit:
	pass


class Radius:
	'''
	classdocs
	'''


	def __init__(self, distance, unit):
		self.distance_ = Distance(distance, unit)
	

	def bend(self):
		return Radius(self.distance_.val_ / RIC, self.distance_.unit_)


	def toM(self):
		return self.distance_.toM()
	

	def toKm(self):
		return self.distance_.toM()


	def toString(self):
		return self.distance_.toString()
	
	
	def toBoundingBox(self, addr):
		return getBoundingBox(addr.getLat(), addr.getLng(), self.bend())		

	def toBoundingBoxLatLng(self, lat, lng):
		return getBoundingBox(lat, lng, self.bend())		

	
def createRadius(request):
	radius = None
	if 'r' in request.GET:
		r = request.GET['r']
		distance = int(re.search('([0-9]+).*', r).group(1))
		unit = re.search('[0-9]+(.*)', r).group(1)
		if unit not in RADIUS_UNIT_LIST:
			raise InvalidRadiusUnit
		radius = Radius(distance, unit)
	else:
		radius = Radius(1, 'km')
	return radius
	

def createRadiusList():
	radiusList = []
	for r in RADIUS_LIST:
		distance = int(re.search('([0-9]+).*', r).group(1))
		unit = re.search('[0-9]+(.*)', r).group(1)
		if unit not in RADIUS_UNIT_LIST:
			raise InvalidRadiusUnit
		radiusList.append(Radius(distance, unit))
	return radiusList
		
		